import { createRouter, createWebHashHistory } from "vue-router";
import { checkStatus, clearStatus } from "../utils/loginStatus.js";
import { Toast } from "vant";
let firstLogin = true;
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/UserModuleViews/Login.vue"),
  },
  {
    path: "/",
    name: "index",
    redirect: "/list",
    component: () => import("@/views/Home.vue"),
    children: [
      {
        path: "/feedback",
        name: "feedback",
        component: () => import("@/views/MyModuleViews/Feedback.vue"),
      },
      {
        path: "/list",
        name: "list",
        component: () => import("@/views/FindModuleViews/List.vue"),
      },
      {
        path: "/discover",
        name: "discover",
        component: () => import("@/components/BBSModuleComponents/Discover.vue"),
      },
      {
        path: "/user",
        name: "user",
        component: () => import("@/views/UserModuleViews/User.vue"),
      },
      {
        path: "/videoDetail",
        name: "videoDetail",
        component: () => import("@/views/FindModuleViews/VideoDetail.vue"),
      },
      {
        path: "/articleDetail",
        name: "articleDetail",
        component: () => import("@/views/FindModuleViews/ArticleDetail.vue"),
      },
      {
        path: "/post-index",
        name: "postindex",
        component: () => import("@/views/BBSModuleViews/PostIndex.vue"),
      },
    ],
  },
  {
    path: "/addPost",
    name: "addPost",
    component: () => import("@/views/BBSModuleViews/AddPost.vue"),
  },
  {
    path: "/publishWork",
    name: "publishWork",
    component: () => import("@/views/FindModuleViews/PublishWork.vue"),
  },
  {
    path: "/user-detail",
    name: "user-detail",
    component: () => import("@/views/MyModuleViews/UserDetail.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () => import("@/views/UserModuleViews/Register.vue"),
  },
  {
    path: "/forget",
    name: "forget",
    component: () => import("@/views/UserModuleViews/ChangePassword.vue"),
  },
  {
    path: "/MyBBSList",
    name: "MyBBSList",
    component: () => import("@/views/MyModuleViews/MyBBSList.vue"),
  },
  {
    path: "/my-find-list",
    name: "my-find-list",
    component: () => import("@/views/MyModuleViews/MyFindList.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (firstLogin && !localStorage.getItem("user")) {
    firstLogin = false;
    return next("/login");
  }
  if (to.name === "forget" || to.name === "register" || to.name === "login") {
    clearStatus();
    return next();
  }
  if (!checkStatus()) {
    Toast.fail({
      message: "登录信息失效，请重新登录",
      duration: 1000,
      forbidClick: true,
      onClose: function () {
        //clearStatus()
        return next("/login");
      },
    });
  } else {
    next();
  }
});

export default router;
